package com.mgee.netty.server.configure;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 线程池配置
 * @author mileswan
 *
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer{
     /*
    此处成员变量应该使用@Value从配置中读取
     */
	@Value("${task.corePoolSize:10}")
    private int corePoolSize;
	
	@Value("${task.maxPoolSize:200}")
    private int maxPoolSize;
	
	@Value("${task.queueCapacity:200}")
    private int queueCapacity;
	
	@Value("${task.keepAliveSeconds:60}")
	private int keepAliveSeconds;
	
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
